package org.jeecg.modules.xl.customerType.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.xl.customerType.entity.XlCustomerPurchaseUser;
import org.jeecg.modules.xl.customerType.entity.XlCustomerType;
import org.jeecg.modules.xl.customerType.service.IXlCustomerPurchaseUserService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.xl.customerType.service.IXlCustomerTypeService;
import org.jeecg.modules.xl.product.service.IXlProductInfoService;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: xl_customer_purchase_user
 * @Author: jeecg-boot
 * @Date:   2024-10-27
 * @Version: V1.0
 */
@Api(tags="xl_customer_purchase_user")
@RestController
@RequestMapping("/xl/xlCustomerPurchaseUser")
@Slf4j
public class XlCustomerPurchaseUserController extends JeecgController<XlCustomerPurchaseUser, IXlCustomerPurchaseUserService> {
	@Autowired
	private IXlCustomerPurchaseUserService xlCustomerPurchaseUserService;
	@Autowired
	private IXlCustomerTypeService customerTypeService;
	
	/**
	 * 分页列表查询
	 *
	 * @param xlCustomerPurchaseUser
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "xl_customer_purchase_user-分页列表查询")
	@ApiOperation(value="xl_customer_purchase_user-分页列表查询", notes="xl_customer_purchase_user-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<XlCustomerPurchaseUser>> queryPageList(XlCustomerPurchaseUser xlCustomerPurchaseUser,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<XlCustomerPurchaseUser> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerPurchaseUser, req.getParameterMap());
		Page<XlCustomerPurchaseUser> page = new Page<XlCustomerPurchaseUser>(pageNo, pageSize);
		queryWrapper.lambda().eq(XlCustomerPurchaseUser::getIsDeleted, 0);
		IPage<XlCustomerPurchaseUser> pageList = xlCustomerPurchaseUserService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param xlCustomerPurchaseUser
	 * @return
	 */
	@AutoLog(value = "xl_customer_purchase_user-添加")
	@ApiOperation(value="xl_customer_purchase_user-添加", notes="xl_customer_purchase_user-添加")
	@RequiresPermissions("xl:xl_customer_purchase_user:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody XlCustomerPurchaseUser xlCustomerPurchaseUser) {
		xlCustomerPurchaseUserService.save(xlCustomerPurchaseUser);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param xlCustomerPurchaseUser
	 * @return
	 */
	@AutoLog(value = "xl_customer_purchase_user-编辑")
	@ApiOperation(value="xl_customer_purchase_user-编辑", notes="xl_customer_purchase_user-编辑")
	@RequiresPermissions("xl:xl_customer_purchase_user:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody XlCustomerPurchaseUser xlCustomerPurchaseUser) {
		xlCustomerPurchaseUserService.updateById(xlCustomerPurchaseUser);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "xl_customer_purchase_user-通过id删除")
	@ApiOperation(value="xl_customer_purchase_user-通过id删除", notes="xl_customer_purchase_user-通过id删除")
	@RequiresPermissions("xl:xl_customer_purchase_user:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		xlCustomerPurchaseUserService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "xl_customer_purchase_user-批量删除")
	@ApiOperation(value="xl_customer_purchase_user-批量删除", notes="xl_customer_purchase_user-批量删除")
	@RequiresPermissions("xl:xl_customer_purchase_user:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.xlCustomerPurchaseUserService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "xl_customer_purchase_user-通过id查询")
	@ApiOperation(value="xl_customer_purchase_user-通过id查询", notes="xl_customer_purchase_user-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<XlCustomerPurchaseUser> queryById(@RequestParam(name="id",required=true) String id) {
		XlCustomerPurchaseUser xlCustomerPurchaseUser = xlCustomerPurchaseUserService.getById(id);
		if(xlCustomerPurchaseUser==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(xlCustomerPurchaseUser);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param xlCustomerPurchaseUser
    */
    @RequiresPermissions("xl:xl_customer_purchase_user:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerPurchaseUser xlCustomerPurchaseUser) {
        return super.exportXls(request, xlCustomerPurchaseUser, XlCustomerPurchaseUser.class, "采购人员");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("xl:xl_customer_purchase_user:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setSheetNum(1);	//只导入一个sheet数据
			params.setStartSheetIndex(0);	//从第一个sheet开始导入
			params.setNeedSave(true);
			try {
				List<XlCustomerPurchaseUser> list = ExcelImportUtil.importExcel(file.getInputStream(), XlCustomerPurchaseUser.class, params);
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				service.saveBatch(list);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if(msg!=null && msg.indexOf("Duplicate entry")>=0){
					return Result.error("文件导入失败:有重复数据！");
				}else{
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

	 /**
	  * 导出excel模版
	  * @param request
	  */
	 @ApiOperation(value="导出采购人员excel模版", notes="导出采购人员excel模版")
	 @RequiresPermissions("xl:xl_customer_purchase_user:importExcel")
	 @RequestMapping(value = "/downloadTemplateXls")
	 public ModelAndView downloadTemplateXls(HttpServletRequest request) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>();
		 Map<String, Object> userSheet = new HashMap<>();
		 ExportParams userSheetParams = new ExportParams("采购人员导入模版", "导入人:" + sysUser.getRealname(),"采购人员导入模版");
		 userSheetParams.setType(ExcelType.XSSF);
		 userSheet.put(NormalExcelConstants.CLASS, XlCustomerPurchaseUser.class);
		 userSheet.put(NormalExcelConstants.PARAMS, userSheetParams);
		 //导出所有渠道清单
		 userSheet.put(NormalExcelConstants.DATA_LIST, Lists.newArrayList());
		 listMap.add(userSheet);


		 Map<String, Object> typeSheet = new HashMap<String, Object>();
		 ExportParams storeSheetParams = new ExportParams("渠道清单","渠道清单", ExcelType.XSSF);
		 typeSheet.put(NormalExcelConstants.CLASS, XlCustomerType.class);
		 typeSheet.put(NormalExcelConstants.PARAMS, storeSheetParams);
		 //导出所有渠道清单
		 typeSheet.put(NormalExcelConstants.DATA_LIST, customerTypeService.list());
		 listMap.add(typeSheet);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.FILE_NAME, "采购人员导入模板");
		 mv.addObject(NormalExcelConstants.MAP_LIST, listMap);
		 return mv;
	 }

}
